package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//@Transactional mongodb的事务必须是复制集的方式
public class StrategyThemeServiceImpl implements IStrategyThemeService{
    @Autowired
    private StrategyThemeRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);//把id设置为null
        repository.save(strategyTheme);//存入strategyTheme对象

    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        repository.save(strategyTheme);//编辑和保存是一样的,更新之后则要保存strategyTheme对象

    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public StrategyTheme get(String id) {
        //orEls,查询id,存在就返回,不承诺在就返回null
        return repository.findById(id).orElse(null);

    }

    @Override
    public List<StrategyTheme> list() {
        //查询所有
        return repository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {

        //分页查询
        //查询对象
        Query query = new Query();
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,StrategyTheme.class,query,pageable);


    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {

        if (StringUtils.hasLength(strategyTheme.getId())){
            //update
            //特殊案例,页面更新的数据,刚好跟集合中字段个数一致
            //所以这种等价于全量的更新
            this.update(strategyTheme);
        }else {
            //save
            this.save(strategyTheme);
        }

    }


}
